# -*- coding: utf-8-*-
from openerp.osv import osv


# 微信企业号菜单
class sync_menu_wizard(osv.osv_memory):
    _name = 'sync.menu.wizard'
    _description = u"微信菜单同步操作"

    def _check_menu_vals(self, vals):
        if 'button' not in vals:
            raise osv.except_osv(u'错误', u'生成的同步信息错误，无法同步')
        if len(vals['button']) > 3:
            raise osv.except_osv(u'错误', u'一级菜单不应该超过三个')

        for menu in vals['button']:
            if 'sub_button' in menu and len(menu['sub_button']) > 5:
                raise osv.except_osv(u'错误', u'二级此单不应该超过5个')

        return True

    def sync_menu(self, cr, uid, ids, context=None):
        context = context or {}
        active_ids = context.get('active_ids')
        model = self.pool.get(context.get('active_model'))

        if model and active_ids:
            agent_id, vals = model.gather_menu_vals(cr, uid, active_ids, context=context)
            self._check_menu_vals(vals)
            model.sync_menu(cr, uid, agent_id, vals, context=context)

            # 将所有同步的菜单标记为已同步，其他的菜单全部变成未同步
            unsync_menu_ids = model.search(cr, uid, [('id', 'not in', active_ids)], context=context)
            model.write(cr, uid, active_ids, {'synced': True}, context=context)
            model.write(cr, uid, unsync_menu_ids, {'synced': False}, context=context)
        else:
            raise osv.except_osv(u'错误', u'没有选中任何需要同步的数据')
